package com.fengba.nanzhi.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.tabbar03.SubmitOrder;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by duan on 2018/4/2.
 */

public class Login extends AppCompatActivity {


    //手机号
    private EditText Iphone;
    //密码
    private EditText Ipassowrd;
    //眼睛图片 ImageButton
    private ImageButton eye;
    //叉叉
    private ImageButton IBclose;
    //登陆
    private Button Bindex;
    //注册
    private TextView NewUser;
    //忘记密码
    private TextView ForgetPass;
    //菊花
    private ProgressBar Ljuhua;


    public Login() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fx_login);
        Ljuhua = (ProgressBar) findViewById(R.id.Ljuhua);
        /**
         * 设置状态栏
         */
        //super.onCreate(savedInstanceState);
        //initWindow();
        Iphone = (EditText) findViewById(R.id.ETphone);
        Iphone.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        Ipassowrd = (EditText) findViewById(R.id.ETpassword);
        /**
         * 显示xx
         */
        Ipassowrd.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ////Log.i(TAG, "输入文字中的状态，count是输入字符数");

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

                ////Log.i(TAG, "输入文本之前的状态");
            }

            @Override
            public void afterTextChanged(Editable s) {
                ////Log.i(TAG, "输入文字后的状态");
                IBclose.setVisibility(View.VISIBLE);
            }
        });

        /**
         * 返回
         */
        ImageButton Lbtn01= (ImageButton) findViewById(R.id.Lbtn01);
        Lbtn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        /**
         * 更换眼睛
         */
        eye = (ImageButton) findViewById(R.id.eye);
        eye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int type = Ipassowrd.getInputType();
                if (type == 109) {
                    Ipassowrd.setInputType(129);
                    ((ImageButton) view).setImageDrawable(getResources().getDrawable(R.mipmap.img_0003));
                } else {
                    Ipassowrd.setInputType(109);
                    ((ImageButton) view).setImageDrawable(getResources().getDrawable(R.mipmap.img_0002));
                }
            }
        });
        /**
         * 叉叉
         */
        IBclose = (ImageButton) findViewById(R.id.IBclose);
        IBclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Ipassowrd.setText("");
                IBclose.setVisibility(View.INVISIBLE);
            }

        });
        /**
         * 登录POST
         */
        Bindex = (Button) findViewById(R.id.Bindex);
        Bindex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Ljuhua.setVisibility(ProgressBar.VISIBLE);
                    if (Iphone.length() == 11) {/*
                        OkHttpClient client = new OkHttpClient();
                        //构建FormBody，传入要提交的参数
                        FormBody formBody = new FormBody
                                .Builder()
                                .add("account", String.valueOf(Iphone.getText()))
                                .add("password", String.valueOf(Ipassowrd.getText()))
                                .build();
                        final Request request = new Request.Builder()
                                .url(UrlUtil.UrlFX + "api/user/land")
                                .post(formBody)
                                .build();
                        Call call = client.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                //ToastUtil.showToast(PostParameterActivity.this, "Post Parameter 失败");
                                ////System.out.println(e.getMessage());
                                ToastUtil.showToast(Login.this,"网络错误",Ljuhua);

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                //final String responseStr = response.body().string();
                                //ToastUtil.showToast(PostParameterActivity.this, "Code：" + String.valueOf(response.code()));
                                try {
                                    String json = response.body().string();
                                    JSONObject jsonObject = new JSONObject(json);
                                    final String message = (String) jsonObject.get("message");
                                    //System.out.println("message " + message);
                                    //System.out.println("jsonObject " + jsonObject);
                                    if (jsonObject.get("code").equals(0)) {
                                        //JSONObject data = (JSONObject) jsonObject.get("data");
                                        *//**
                                         * 忘记密码
                                         *//*
                                        Intent intent = new Intent(Login.this, com.fengba.nanzhi.fengba.MainActivity.class);
                                        //intent.putExtra("data", (Parcelable) data);
                                        startActivity(intent);
                                    } else {
                                        ToastUtil.showToast(Login.this,message,Ljuhua);
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });


                    */
                        OKManager.getInstance().type0001(String.valueOf(Iphone.getText()), String.valueOf(Ipassowrd.getText()), new OKManager.func4() {
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    if (jsonObject.get("code").equals(0)) {

                                        //获取data
                                        JSONObject data = jsonObject.getJSONObject("data");
                                        //保存数据
                                        Preferences.setParam(Login.this,"user_info",data.toString());
                                        //保存账号
                                        Preferences.setParam(Login.this,"account",Iphone.getText().toString());
                                        //保存密码
                                        Preferences.setParam(Login.this,"password",Ipassowrd.getText().toString());

                                       // todayLuckYou();
                                        new Handler().postDelayed(new Runnable(){
                                            public void run() {
                                                //Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                                                //finish();
                                                todayLuckYou();
                                                setBasicSetup(1);
                                                setBasicSetup(4);
                                            }
                                        }, 150);


                                    } else {
                                        //jsonArray1 = jsonObject.getJSONArray("data");
                                        Toast.makeText(Login.this, jsonObject.get("message").toString(), Toast.LENGTH_SHORT).show();
                                        Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(String string) {
                                Toast.makeText(Login.this, "网络错误", Toast.LENGTH_SHORT).show();
                                Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                            }
                        });
                    }else {
                        Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                        Toast.makeText(Login.this, "请输入正确手机号", Toast.LENGTH_SHORT).show();
                        Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                    }

            }

        });

        /**
         * 立即注册
         */
        NewUser = (TextView) findViewById(R.id.newUser);
        NewUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Login.this, Reg.class);
                startActivity(intent);
            }

        });
        /**
         * 忘记密码
         */
        ForgetPass = (TextView) findViewById(R.id.forgetPass);
        ForgetPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Login.this, ForGet.class);
                startActivity(intent);
            }

        });


    }//都在这里打

    private void todayLuckYou(){
        Object user_info = Preferences.getParam(this,"user_info","");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());
            //id
            String id = myJson.get("id").toString();
            //账号
            String account = myJson.get("account").toString();
            //密码
            String password = String.valueOf(Ipassowrd.getText());
            //registrationId
            String registrationId = "1000";
            //
            //Log.e("ii",id+"|"+account+"|"+password+"|"+registrationId);
            OKManager.getInstance().type0004(id, account, password, registrationId, new OKManager.func4() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    try {
                        if(Integer.parseInt(jsonObject.get("code").toString()) == 0){

                            String message = jsonObject.get("message").toString();
                            Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();

                            new Handler().postDelayed(new Runnable(){
                                public void run() {
                                    Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                                    finish();
                                }
                            }, 150);

                        }else{
                            String message = jsonObject.get("message").toString();
                            Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
                            new Handler().postDelayed(new Runnable(){
                                public void run() {
                                    Ljuhua.setVisibility(ProgressBar.INVISIBLE);
                                    finish();
                                }
                            }, 150);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String string) {
                    Toast.makeText(Login.this, "网络错误", Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 1-2-3-4
     * 增、删、改、查
     */
    public void setBasicSetup(int type) {
        String account = null;
        try {
            Object user_info = Preferences.getParam(Login.this, "user_info", "");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            account = myJson.get("account").toString();
            //System.out.println("account"+account);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (type == 1) {
            //设置别名（新的调用会覆盖之前的设置）
            JPushInterface.setAlias(this, 0, account);
            //设置标签（同上）
            JPushInterface.setTags(this, 0, setUserTags(account));
        } else if (type == 2) {
            //删除别名
            JPushInterface.deleteAlias(this, 0);
            //删除指定标签
            //JPushInterface.deleteTags(this, 0, setUserTags());
            //删除所有标签
            JPushInterface.cleanTags(this, 0);
        } else if (type == 3) {
            //增加tag用户量(一般都是登录成功设置userid为目标，在别处新增加比较少见)
            //JPushInterface.addTags(this, 0, setUserTags());
        } else if (type == 4) {
            //查询所有标签
            JPushInterface.getAllTags(this, 0);
            //查询别名
            JPushInterface.getAlias(this, 0);
            //查询指定tag与当前用户绑定的状态（MyJPushMessageReceiver获取）
            JPushInterface.checkTagBindState(this, 0, account);
            //获取注册id
            JPushInterface.getRegistrationID(this);
        }
    }

    /**
     * 标签用户
     * @return
     */

    private static Set<String> setUserTags(String account) {
        //添加3个标签用户（获取登录userid较为常见）
        Set<String> tags = new HashSet<>();
        tags.add(account);
        return tags;
    }

}
